<?php
/**
 * Created by PhpStorm.
 * User: 68008000
 * Date: 2017/12/6
 * Time: 22:48
 */

namespace app\common\model;


use think\Model;
use think\Validate;

class Admin extends Model
{
    //链接数据库
    protected $table = 'shop_administrators';
    protected $pk = 'aid';
    //数据完成自动加密
    public function setPasswordAttr($data)
    {
        return MD5($data);
    }
    //用户新增
    public function add($data){
        $result = $this->validate(true)->save($data);
        if(false === $result){
            // 验证失败 输出错误信息
            return ['valid'=>0,'msg'=>$this->getError()];
        }else{
            return ['valid'=>1,'msg'=>'添加成功'];
        }
    }
    //编辑
    public function edit($data){
        p($data);
        //1.验证
        $validata = new Validate(
            [
                'username'=>'require',
                'password'=>'require',
            ],[
                'username.require'=>'请输入用户名',
                'password.require'=>'请输入密码',
            ]
        );
        if(!$validata->check($data)){
            return ['valid'=>0,'msg'=>$validata->getError()];
        }
        //2.验证管理员是否存在
        $userInfo = $this->where("uid != {$data['uid']}")->where('username',$data['username'])->find();
        if ($userInfo){
            return ['valid'=>0,'msg'=>'管理员存在'];
        }
        //3.执行修改
        $data['password'] = md5($data['password']);
        $this->save($data,[$this->pk => $data['uid']]);
        return ['valid'=>1,'msg'=>'编辑成功'];
    }
    //分配权限
    public function setAuth($data){
        p($data);
        $uid = input('param.uid');
        //3.文章标签中间表添加
        Groupaccess::where('uid',$uid)->delete();
        foreach ($data['group_id'] as $k=>$v){
            $Groupaccess =new Groupaccess([
                'uid'=>$uid,
                'group_id'=>$v
            ]);
            $Groupaccess->save();
        }
    }
}